import hashlib
from pathlib import Path

import exifread
from PIL import Image, JpegImagePlugin

# https://github.com/python-pillow/Pillow/issues/1138#issuecomment-871537090
JpegImagePlugin._getmp = lambda x: None


# 用于图片修复和图片转换
def fix_orient_and_convert(path):
    im = Image.open(path)
    if im.format != 'JPEG':
        return im.width, im.height
    with open(path, "rb") as file_handle:
        tags = exifread.process_file(file_handle, details=False)

    if_rotate = False
    if "Image Orientation" in tags.keys():
        orientation = tags["Image Orientation"]
        val = orientation.values
        if 2 in val:
            val += [4, 3]
        if 5 in val:
            val += [4, 6]
        if 7 in val:
            val += [4, 8]
        if 3 in val:
            im = im.transpose(Image.ROTATE_180)
            if_rotate = True
        if 4 in val:
            im = im.transpose(Image.FLIP_TOP_BOTTOM)
            if_rotate = True
        if 6 in val:
            im = im.transpose(Image.ROTATE_270)
            if_rotate = True
        if 8 in val:
            im = im.transpose(Image.ROTATE_90)
            if_rotate = True
    if if_rotate:
        im.format = 'JPEG'
        im.save(path, format='JPEG', quality='keep')
    return im.width, im.height


# 图片路径+图片名称=hash
# return hash+文件名称
def gen_img_hash(path):
    if path is None:
        return None
    img_path = Path(path)
    suffix = img_path.suffix
    if suffix is None:
        return
    suffix = suffix.split('?')[0]
    img_not_suffix = str(img_path.parent) + "/" + img_path.stem
    md5 = string_to_md5(img_not_suffix)
    return md5 + suffix


def string_to_md5(string):
    # 创建一个 MD5 对象
    md5 = hashlib.md5()
    # 将字符串编码为字节并计算 MD5 摘要
    md5.update(string.encode('utf-8'))
    # 获取 MD5 摘要的十六进制表示
    md5_digest = md5.hexdigest()
    return md5_digest


if __name__ == "__main__":
    path = "https://test-camera-content-1330240477.cos.ap-shanghai.myqcloud.com/2025/08/13/313117141560336384/2276.png?q=099"
    print(gen_img_hash(path))
